var JQT = $.jQTouch({
	icon:'kilo.png',
	fixedViewport:true
});
var db;   //定义数据库对象
$(document).ready(function(){
    $("#createEntry form").submit(createEntry);
	$("#settings form").submit(saveSettings);
	$("#settings").bind("pageAnimationStart",loadSettings);
	$("#dates li a").click(function(){
		var dateOffset = this.id;  //得到当前的点击的链接ID
		var date = new Date();     //创建日期对象
		date.setDate(date.getDate()-dateOffset);
		var __tempdate__ = date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
		sessionStorage.currentDate = __tempdate__;
		refreshEntries();
	});
});

var shortName = "Kilo";
var version = "1.0";        
var displayName = "Kilo";   //显示名字，在调试器中显示的名字
var maxSize = 65536;   //设置数据库数据最大限制
db = openDatabase(shortName,version,displayName,maxSize);  //打开数据库链接
db.transaction(
	function(transaction){
		//判断数据表是否存在，如果不存在则创建一个新的数据表
		transaction.executeSql(
			'CREATE TABLE IF NOT EXISTS entries' +
			'(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,' +
			'date DATE NOT NULL,food TEXT NOT NULL,' +
			'calories INTEGER NOT NULL);'
			);
	}
);

function saveSettings(){
	//设置本地存储对象
	localStorage.age = $("#age").val();
	localStorage.budget = $("#budget").val();
	localStorage.weight = $("#weight").val();
	JQT.goBack();
	return false;
}
function loadSettings(){
	//读取本地数据
	$("#age").val(localStorage.age);
	$("#budget").val(localStorage.budget);
	$("#weight").val(localStorage.weight);
}
function refreshEntries(){
	var currentDate = sessionStorage.currentDate;
	$("#date h1").text(currentDate);
}
function createEntry(){
	var date = sessionStorage.currentDate;
	var calories = $('#calories').val();
	var food = $("#food").val();
	db.transaction(
		function(transaction){
			transaction.executeSql('INSERT INTO entries (date,calories,food) VALUES (?,?,?);',[date,calories,food],
			function(){
				refreshEntries();
				JQT.goBack();
			}),
			errorHandler
		}
	);
	return false;	
}
function errorHandler(transaction,error){   //系统出错函数处理
	alert("Oops,Error was "+error.message+" (Code + " + error.code + ")");
	return true;
}
